'use strict';

let Fiber = require('fibers');
let models = require('../modules/models/index');
let attendanceService = require('../modules/services/attendance');

let AttendanceStatus = models.AttendanceStatus;

let SchoolDao = models.SchoolDao;
let RawAttendanceDao = models.RawAttendanceDao;
let AttendanceValueDao = models.AttendanceValueDao;

function main() {
    let now = new Date();

    let school = SchoolDao.findOne({
        name: '合肥绿怡小学'
    });

    updateSchoolStatus(school, now);
}

function updateSchoolStatus(school, time) {
    let checkTimes = getCheckTimeSetToday(school, time);
    let checkTimeIndex = getIndexToCheck(checkTimes, time);

    school.grades.forEach(grade => {
        grade.natureClasses.forEach(natureClass => {
            natureClass.students.forEach(student => {
                updateStudentStatus(student, checkTimes, checkTimeIndex, time);
            });
        });
    });
}

function updateStudentStatus(student, checkTimes, checkTimeIndex, time) {
    let checkTime = checkTimes[checkTimeIndex];

    let startMinutes = toMinutes(checkTime.startHour, checkTime.startMinute);
    let endMinutes = toMinutes(checkTime.endHour, checkTime.endMinute);

    // 获取最新的原始考勤信息
    let rawAttendances = RawAttendanceDao.find({
        student: student.id
    }).sort((a1, a2) => {
        return a1.time < a2.time;
    });

    let rawAttendance = null;
    if ( rawAttendances.length > 0 ) {
        rawAttendance = rawAttendances[0];
    }

    let attendance = attendanceService.getAttendanceOfStudentToday(student);
    let attendanceValue = attendance.values[checkTimeIndex];
    let attendanceMinutes = toMinutes(rawAttendance.time.getHours(), rawAttendance.time.getMinutes);

    // 是否在开始之前（enterStatus正常）
    if ( attendanceMinutes <= startMinutes ) {
        attendanceValue.enterStatus = AttendanceStatus.Attended;
    }
    // 是否在结束之后（检查exitStatus是否正常）
    else if ( attendanceMinutes >= endMinutes ) {
        attendanceValue.exitStatus = AttendanceStatus.Attended;
    }

    // TODO：检查是否旷课

    // 更新写入数据库
    AttendanceValueDao.update(attendanceValue);
}

function getIndexToCheck(checkTimes, time) {
    return checkTimes.findIndex(checkTime => {
        let hour = time.getHours();
        let minute = time.getMinutes();

        let nowMinutes = toMinutes(hour, minute);
        let startMinutes = toMinutes(checkTime.startHour, checkTime.startMinute);
        let endMinutes = toMinutes(checkTime.endHour, checkTime.endMinute);

        if ( nowMinutes >= startMinutes && nowMinutes <= endMinutes ) {
            return true;
        }
        else if ( nowMinutes >= endMinutes ) {
            return true;
        }

        return false;
    });
}

function getCheckTimesToday(school, time) {
    let day = time.getDay();

    if ( day == 0 ) {
        return school.checkTimeSet.sunday;
    }
    else if ( day == 6 ) {
        return school.checkTimeSet.saturday;
    }
    else {
        return school.checkTimeSet.weekdays;
    }
}

// 将小时和分钟都转换为分钟
function toMinutes(hour, minute) {
    return hour * 60 + minute;
}

new Fiber(main).run();

module.exports = {
    updateSchoolStatus
};
